package com.qst.service.impl;

import com.qst.ExamException;
import com.qst.dao.DAOFactory;
import com.qst.dao.UserDao;
import com.qst.entity.User;
import com.qst.service.UserService;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao = DAOFactory.getDao(UserDao.class);

    @Override
    public User login(String login, String password) {
        User user = userDao.findByLogin(login);
        String msg = null;
        if (user == null) {
            msg = "用户不存在";
        } else if (user.getStatus() != 1) {
            msg = "账户已经被禁用，不能登录";
        } else if (!user.getPasswd().equals(password)) {
            msg = "密码错误啦！";
        }
        if (msg != null) {
            throw new ExamException(msg);
        }
        userDao.updateLastLogin(user.getId(),
                new Timestamp(System.currentTimeMillis()));
        return user;
    }

    @Override
    public void changePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userDao.findById(userId);
        if (!user.getPasswd().equals(oldPassword)) {
            throw new ExamException("原密码错误");
        }
        userDao.updatePassword(userId, newPassword);
    }
}
